/**
 * @Author: bzirs
 * @Date: 2021-05-10 09:38:15
 * @LastEditors: bzirs
 * @LastEditTime: 2022-12-25 20:54:19
 * @FilePath: /vue2-hr-two/src/permission.js
 * @Description:
 * @
 * @Copyright (c) 2022 by bzirs, All Rights Reserved.
 */
import router, { asyncRouters, constantRoutes } from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
// import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

const whitleList = ['/login']

router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  NProgress.start()

  if (token) {
    // 获取用户信息存储vuex
    console.log(store.getters.userId)
    if (!store.getters.userId) {
      await store.dispatch('user/getUserInfo')
      // const
      console.log()
      const arr = asyncRouters.filter(item => store.getters.menus.includes(item.children[0].name))
      arr.push({ path: '*', redirect: '/404', hidden: true })
      router.addRoutes(arr)
      store.commit('menu/updateMenu', [...constantRoutes, ...arr])
      next(to.path)
    }

    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whitleList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }

  NProgress.done()
})

router.beforeEach((to, from, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})

router.afterEach(() => {
  NProgress.done()
})

